from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from django.contrib.auth.models import Permission, ContentType, Group

from users.models import User


class PermissionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeSerialzier(serializers.ModelSerializer):

    class Meta:
        model = ContentType
        fields = ('id','name')

class PermissionSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id','name')

class GroupSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id','name','permissions')

    # def create(self, validated_data):
    #     permissions = validated_data.pop('permissions')
    #     group = Group.objects.create(**validated_data)
    #     # 插入中间权限表
    #     group.permissions.set(permissions)
    #     return group




class AdminSerialzier(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            'id',
            'username',
            'email',
            'mobile',

            'groups',
            'user_permissions',
            'password'
        )
        # fields = '__all__'
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def validate(self,attrs):
        attrs['is_staff'] = True
        raw_password = attrs.get('password')
        attrs['password']=make_password(raw_password)
        return attrs

class AdminGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'